package com.wedo.mall.fragment;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.e.library.fragment.EFragment;
import com.e.library.http.EApi;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.wedo.mall.R;
import com.wedo.mall.activity.goods.GoodsMapActivity;
import com.wedo.mall.activity.main.SearchActivity;
import com.wedo.mall.adapter.GoodsAdapter;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.ptr.Pull2Refresh;

import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索-搜索商品
 * Created by e on 2017/7/15.
 */

public class SearchGoodsFragment extends EFragment<SearchActivity> {

    @BindView(R.id.tv_empty) TextView tv_empty;
    @BindView(R.id.tv_result) TextView tv_result;
    @BindView(R.id.rv_list) XRecyclerView rv_list;
    @BindString(R.string.search_show_goods_with_map) String format;
    private Pull2Refresh<Goods> ptr;

    public static SearchGoodsFragment with(){
        return new SearchGoodsFragment();
    }

    @Override
    protected int layout() {
        return R.layout.fragment_search;
    }

    @Override
    protected void onFragmentCreated(View contentView, Bundle bundle) {
        rv_list.setHasFixedSize(true);
        rv_list.setLayoutManager(new GridLayoutManager(getContext(),2));

        tv_empty.setText(R.string.search_empty);

        ptr = new Pull2Refresh<>();
        GoodsAdapter adapter = new GoodsAdapter(getContext(),null);
        adapter.listener(activity());
        ptr.widget(rv_list).adapter(adapter).url(EApi.GOODS_SEARCH).clazz(Goods.class).emptyWidget(tv_empty).observer(new EObserver() {
            @Override
            public void successful(EResponse response) {
                ptr.limit(response.page_limit);
                List<Goods> list = response.list(Goods.class);
                ptr.finish(list);
                onFinish(ptr.datas().size());
            }

            @Override
            public void failure(String msg) {
                ptr.finish(null);
                onFinish(0);
            }
        }).build();

    }

    private void onFinish(int count){
        if (count == 0){
            tv_result.setVisibility(View.GONE);
        }else {
            tv_result.setVisibility(View.VISIBLE);
            tv_result.setText(String.format(format,count));
        }
    }
    public void search(String keyword){
        if (ptr == null){
            return;
        }
        ptr.param("keyword",keyword).refresh();
    }

    @OnClick(R.id.tv_result)
    protected void onResultClick(){
        GoodsMapActivity.toMap(activity(),ptr.datas());
    }
}
